﻿using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackExchange.Redis
{
    public struct SortedSetItem<T> : IEquatable<SortedSetItem<T>>, IComparable, IComparable<SortedSetItem<T>>
    {
        public SortedSetItem(T element, double score)
        {
            Element = element;
            Score = score;
        }

        public T Element { get; private set; }
        public double Score { get; private set; }

        public int CompareTo(SortedSetItem<T> other)
        {
            return Score.CompareTo(other.Score);
        }

        public int CompareTo(object obj)
        {
            return Score.CompareTo(((SortedSetItem<T>)obj).Score);
        }

        public bool Equals(SortedSetItem<T> other)
        {
            return Element.Equals(other.Element);
        }

        public static bool operator ==(SortedSetItem<T> x, SortedSetItem<T> y)
        {
            return x.Equals(y);
        }
        public static bool operator !=(SortedSetItem<T> x, SortedSetItem<T> y)
        {
            return !x.Equals(y);
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;

            if (obj.GetType() != this.GetType())
            {
                return false;
            }
            return Equals((SortedSetItem<T>)obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public static implicit operator SortedSetEntry(SortedSetItem<T> item)
        {
            var element = JsonSerializer.SerializeToString(item.Element);
            SortedSetEntry entity = new SortedSetEntry(element, item.Score);
            return entity;
        }

        public static implicit operator SortedSetItem<T>(SortedSetEntry entity)
        {
            var itemElement = JsonSerializer.DeserializeFromString<T>(entity.Element);
            SortedSetItem<T> item = new SortedSetItem<T>(itemElement, entity.Score);
            return item;
        }
    }
}
